<?php
namespace app\common\component\help_to_upstart;

use app\common\model\HelpToUpstart;
use app\common\model\HelpGetUpstart;

class HelpToUpstartService {
	public function create($data) {
		$data['order_id'] = 'TO' . date('YmdHis') . rand(1000, 9999);
		$HelpToUpstart = new HelpToUpstart($data);

    	if($HelpToUpstart -> save()) {
    		return [
    			'code' => 0,
    			'message' => '土豪区打款创建成功!',
    			'data' => [
    				'help_to_upstart' => $HelpToUpstart
    			]
    		];
    	}

    	return [
			'code' => -1,
			'message' => '土豪区打款创建失败!'
		];
	}

	public function confirm($help_to_upstart_id) {
		$getHelpToUpstart = HelpToUpstart::get(['help_to_upstart_id' => $help_to_upstart_id]);
		if(!$getHelpToUpstart) {
			return [
				'code' => -1,
				'message' => '订单不存在'
			];
		}

		$getHelpGetUpstart = HelpGetUpstart::get(['help_get_upstart_id' => $getHelpToUpstart -> help_get_upstart_id]);
		if(!$getHelpGetUpstart) {
			return [
				'code' => -1,
				'message' => '订单不存在'
			];
		}

		$currentTime = time();

		\think\Db::startTrans();
		try {
			$getHelpToUpstart -> begin_time = $currentTime;
			$getHelpToUpstart -> status = 2;
			if(!$getHelpToUpstart -> save()) {
				throw new \Exception('确认打款失败');
			}

			$getHelpGetUpstart -> begin_time = $currentTime;
			$getHelpGetUpstart -> status = 2;
			if(!$getHelpGetUpstart -> save()) {
				throw new \Exception('确认打款失败');
			}

			$confirmHelpGetUpstart = (new \app\common\component\help_get_upstart\HelpGetUpstartService()) -> confirm($getHelpToUpstart -> help_get_upstart_id);
			if($confirmHelpGetUpstart['code'] != 0) {
				throw new \Exception($confirmHelpGetUpstart['message']);
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			return [
				'code' => -1,
				'message' => $e -> getMessage()
			];
		}

		return [
			'code' => 0,
			'message' => '确认打款成功'
		];
	}

	public function overtime() {
		$selectHelpToUpstart = HelpToUpstart::where('status = 1 AND over_time < ' . time()) -> select();

		if(empty($selectHelpToUpstart)) {
			return false;
		}

		$currentTime = time();
		foreach($selectHelpToUpstart as $helpToUpstart) {
			$helpToUpstart -> begin_time = $currentTime;
			$helpToUpstart -> status = 8;

			\think\Db::startTrans();
			try {
				if(!$helpToUpstart -> save()) {
					throw new \Exception('超时失败修改');
				}

				if(!HelpGetUpstart::where('help_get_upstart_id', $helpToUpstart -> help_get_upstart_id) -> update([
					'help_to_upstart_id' => 0,
					'begin_time' => $currentTime,
					'status' => 0,
					'sort' => 0
				])) {
					throw new \Exception('超时失败修改');
				}

				\think\Db::commit();
			} catch(\Exception $e) {
				\think\Db::rollback();

				//$e -> getMessage();
			}
		}
	}
}
?>